package cn.cvs.controller;

import cn.cvs.pojo.SysRole;
import cn.cvs.pojo.SysUser;
import cn.cvs.service.SysRoleService;
import cn.cvs.service.SysUserService;
import cn.cvs.utils.Constants;
import cn.cvs.utils.PageSupport;
import com.alibaba.fastjson.JSON;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.apache.ibatis.annotations.Delete;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class SysUserController {

    // 用户
    @Autowired
    private SysUserService sysUserService;
   //角色
    @Autowired
    private SysRoleService sysRoleService;


    //根据角色和用户名查询

    @RequestMapping("/sys/user/list")
    public String findByAccountOrRoleId(@RequestParam(value = "queryRealName", required = false) String queryRealName,
                                        @RequestParam(value = "queryRoleId", required = false) Integer queryRoleId,
                                        @RequestParam(defaultValue="1", required = false) Integer pageIndex,
                                        Model model) {




        try {

            // 设置页面大小
            int pageSize = Constants.pageSize;

            int  totalCount = sysUserService.getUserCount("%"+( queryRealName == null ? "":queryRealName)+"%",queryRoleId);

            PageSupport pages = new PageSupport();
            pages.setCurrentPageNo(pageIndex);
            pages.setPageSize(pageSize);
            pages.setTotalCount(totalCount);
            int totalPageCount = pages.getTotalPageCount();
           //控制首尾页
            if (pageIndex > totalCount){
                pageIndex = totalPageCount;
            }
            List<SysUser>  sysUserList = sysUserService.findSysUser("%"+( queryRealName == null ? "":queryRealName)+"%",queryRoleId,pageIndex,pageSize);

            List<SysRole> roleList = sysRoleService.findAllSysRole(); // 获取所有角色列表
            model.addAttribute("roleList", roleList); // 将角色列表添加到模型
            model.addAttribute("userList", sysUserList); // 将用户列表添加到模型
            model.addAttribute("queryRealName",queryRealName);
            model.addAttribute("queryRoleId",queryRoleId);
            model.addAttribute("totalPageCount",totalPageCount);
            model.addAttribute("totalCount",totalCount);
            model.addAttribute("currentPageNo",pageIndex);
            return "sysUser/list"; // 返回用户列表视图
        }catch (Exception e){
            e.printStackTrace();
            return "redirect:/sysError";
        }



    }





 //查看用户信息
    @RequestMapping("/sys/user/view/{id}")
    public String findByAccountOrRoleId(@PathVariable("id") Integer id, Model model) {
        SysUser  sysUser = sysUserService.getBySysUserId(id);
        model.addAttribute("sysUser",sysUser);
        return "sysUser/view"; // 返回查看用户列表视图
    }

   // 跳转添加
    @RequestMapping("/sys/user/toAdd")
    public String toAdd() {

        return "sysUser/add";
    }

    // 判断用户账号是否存在

    @RequestMapping(value="/sys/user/userExist", produces="application/json;charset=UTF-8")
    @ResponseBody
    public  String getByAccount( @RequestParam("account") String account, Map<String,Object> map ){


        if ( account == null || "".equals(account.trim())){
            map.put("exist",-1);
            map.put("msg","该账号不能为空");
        } else{
            int count = sysUserService.getByAccount(account);
            if ( count > 0){
                map.put("exist",1);
            } else  if ( count == 0){
                map.put("exist",0);
            }
        }

         String data =  JSON.toJSONString(map);
        return data;

    }


    //获取上传文件
    private static  final Logger logger = LoggerFactory.getLogger("/sysUser/add");

    //添加
    @RequestMapping("/sys/user/add")
    public String addSysUser(SysUser sysUser,
                             HttpSession session,
                             HttpServletRequest request,
                             @RequestParam("idPic")MultipartFile idPic,
                             @RequestParam("workPic")MultipartFile workPic
                             ) {
         String idPicPath = null;
         String workPicPath = null;

         //获取上传文件路径
        String path = request.getSession().getServletContext().getRealPath("statics"+ File.separator +"uploadfiles");
        logger.info("uploadFile path =========== > " + path); //向日志文件中记录上传文件的路径


        // 判断文件是否为空 （证件照）
        if(!idPic.isEmpty()){
             String oldFileName = idPic.getOriginalFilename();
            logger.info("uploadFile oldFileName =========== > " + oldFileName); //向日志文件中记录原文件
            String prefix = FilenameUtils.getExtension(oldFileName); // 原文件后缀
            logger.info("uploadFile prefix =========== > " + prefix); //向日志文件中记录原文件后缀
            int filesize = 5000000; //文件上传大小限制
            // 判断文件大小
            if( idPic.getSize() > filesize){ // 上传文件大小不能超过 500K
                request.setAttribute("uploadFileError","* 上传文件大小不能超过 500K ");
                return "sysUser/add";

            } else  if ( prefix.equalsIgnoreCase("jpg") ||
                         prefix.equalsIgnoreCase("png") ||
                         prefix.equalsIgnoreCase("jpeg") ||
                         prefix.equalsIgnoreCase("pneg") ){ // 上传图片格式是否正确
                 //System.currentTimeMillis(); 返回当前时间的毫秒数
               // RandomUtils.nextInt(10000000) 生成一个介于0 （包含）和10000000（不包含） 之间的随机数
                //拼接文件名 列如32456789_Personal.jpg
                String fileName  = System.currentTimeMillis() + RandomUtils.nextInt(1000000) + "_Personal.jpg";
                logger.debug("new fileName =========== > " + idPic.getName()); //记录生成的文件名
                File targetFile = new File(path,fileName); //通过文件路径和文件名创建文件对象
                if(!targetFile.exists()){ //判断文件是否存
                    targetFile.mkdirs();

                }
                //保存文件

                    try {
                        idPic.transferTo(targetFile);
                    } catch (IOException ioException) {
                        ioException.printStackTrace();
                        request.setAttribute("uploadFileError" ," * 上传文件！");
                        return "sysUser/add";
                    }
                 idPicPath = path + File.separator+fileName;

            } else {
                request.setAttribute("uploadFileError","* 上传图片格式不正确");
                return "sysUser/add";
            }

        }

        // 判断文件是否为空 （工作证照）
        if (!workPic.isEmpty()){
            String oldFileName = workPic.getOriginalFilename(); // 原文件名
            logger.info("uploadFile oldFileName =========== > " + oldFileName); //向日志文件中记录原文件名
             String prefix = FilenameUtils.getExtension(oldFileName); // 原文件后缀
            logger.info("uploadFile prefix =====================>" + prefix); //向日志文件中记录原文件后缀
            int filesize = 500000; // 文件上传大小限制

            // 判断文件上传大小
            if (workPic.getSize() > filesize){// 上传文件大小不能超过 500K
                request.setAttribute("uploadFileError","* 上传文件大小不能超过 500K ");
                return "sysUser/add";
            } else if ( prefix.equalsIgnoreCase("jpg") ||
                    prefix.equalsIgnoreCase("png") ||
                    prefix.equalsIgnoreCase("jpeg") ||
                    prefix.equalsIgnoreCase("pneg") ){// 上传图片格式是否正确
                //System.currentTimeMillis(); 返回当前时间的毫秒数
                // RandomUtils.nextInt(10000000) 生成一个介于0 （包含）和10000000（不包含） 之间的随机数
                //拼接文件名 列如32456789_Personal.jpg
              String fileName = System.currentTimeMillis() +RandomUtils.nextInt(1000000) + "_Personal.jpg";
              logger.debug("new fileName==========" + workPic.getName()); // 记录生成的文件名
                File targetFile = new File(path,fileName); //通过文件路径和文件名创建文件对象
                if (!targetFile.exists()){// 判断文件是否存在
                    targetFile.mkdirs();
                }

                // 保存文件
                try {
                    workPic.transferTo(targetFile);
                } catch (IOException ioException) {
                    ioException.printStackTrace();
                    request.setAttribute("uploadFileError" ,"* 上传失败！");
                    return"/sysUser/add";
                }
                workPicPath = path + File.separator + fileName;

            } else {
                request.setAttribute("uploadFileError","* 上传图片格式不正确");
                return "sysUser/add";
            }

        }
        try {
            // 执行添加
            sysUser.setCreatedUserId(((SysUser)session.getAttribute(Constants.USER_SESSION)).getId());// 获取创建人id
            //设置用户对象的证件照地址
            sysUser.setIdPicPath(idPicPath);
            //设置用户对象的工作照地址
            sysUser.setWorkPicPath(workPicPath);
            if ( sysUserService.addSysUser(sysUser) > 0){ // 判断是否添加成功

                return "redirect:/sys/user/list";
            }
        } catch (Exception exception) {
            exception.printStackTrace();
            logger.error("保存用户信息失败");
        }

        return "/sysUser/add";
    }


    //删除
    @RequestMapping( value="/sys/user/del/{id}", produces ="application/json;charset=UTF-8")
    @ResponseBody
    public String delSysUser(@PathVariable("id") Integer id ,Map<String,String> map) {
        int i = sysUserService.delSysUser(id);
         String delResult = "false";
         if (i > 0){
             delResult = "true";
         } else if ( i  == 0){
             delResult = "notexist";
         }
         map.put("delResult",delResult);
         String data = JSON.toJSONString(map);
        return data;
    }


    // 根据编号获取数据
    @RequestMapping("/sys/user/toUpdate")
    public String findByAccountOrRoleIds(@RequestParam("uid") Integer id, Model model) {
        SysUser  sysUser = sysUserService.getBySysUserId(id);
        model.addAttribute("sysUser",sysUser);
        return "sysUser/update";
    }

  // 修改
  @RequestMapping("/sys/user/update")
  public String updateSysUser(SysUser sysUser,HttpSession session) {

      // 修改人id
      sysUser.setUpdatedUserId(((SysUser)session.getAttribute(Constants.USER_SESSION)).getId());// 获取创建人id
      // 修改时间
      sysUser.setUpdatedTime(new Date());
      int count = sysUserService.updateSysUser(sysUser);
      if ( count > 0 ){
          return "redirect:/sys/user/list";
      }
      return "sysUser/update";
  }


  // 跳转修改密码页面
    @RequestMapping("/sys/user/toUpdatePwd")
    public String toPwd(){
        return "sysUser/updatePassword";
    }

    // 判断用户密码是否一样
    @RequestMapping(value="/sys/user/checkOldPwd", produces="application/json;charset=UTF-8")
    @ResponseBody
    public  String  oldPassword(@RequestParam("oldPassword")  String oldPassword,Map<String,String> map,HttpSession session){
      String result = "";

      try {
          //获取登录密码
      String password = ((SysUser)session.getAttribute(Constants.USER_SESSION)).getPassword();
        // 判断session 是否为空
       if ( session == null){
           result  = "sessionerror";
       } else if(oldPassword==null || oldPassword == ""){
           result = "error";
       } else  if (password .equals(oldPassword)){
           result = "true";
       } else {
           result = "false";
       }

        } catch (Exception exception) {
            exception.printStackTrace();
        }
        map.put("result",result);
        String data = JSON.toJSONString(map);
        return data;
    }


  // 修改密码
    @RequestMapping("/user/savePassword")
  public String savePassword( @RequestParam("newPassword") String password ,HttpSession session) {

        int id = ((SysUser)session.getAttribute(Constants.USER_SESSION)).getId();

        int count  = sysUserService.savePassword(password,id);
        if (count > 0){
            session.setAttribute(Constants.SYS_MESSAGE,"密码修改成功");

            return "sysUser/updatePassword";
        } else {
            session.setAttribute(Constants.SYS_MESSAGE,"密码修改失败");
            return "sysUser/updatePassword";
        }


    }




}
